package activity

import (
	"context"

	"mall/common/globalkey"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/promotion/model"
	"mall/service/promotion/rpc/internal/svc"
	"mall/service/promotion/rpc/internal/utils/errorhandler"
	"mall/service/promotion/rpc/types/promotion"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendDeleteActivityProductBrandLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendDeleteActivityProductBrandLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendDeleteActivityProductBrandLogic {
	return &BackendDeleteActivityProductBrandLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendDeleteActivityProductBrandLogic) BackendDeleteActivityProductBrand(
	in *promotion.ActivityRelationshipInfo,
) (*promotion.BaseResp, error) {
	if in.ActivityId == 0 || len(in.BrandIds) == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	data, err := l.svcCtx.Activity.FindOneNoCache(l.ctx, nil, in.ActivityId)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if data.Status != uint16(globalkey.StatusPending) && data.Status != uint16(globalkey.StatusRejected) {
		return nil, errorx.NewInvalidArgumentError(i18n.ConstraintError)
	}

	bindRel := &model.PromotionActivityBindRel{}
	for _, bid := range in.BrandIds {
		if bid > 0 {
			bindRel.DelBrandIds = append(bindRel.DelBrandIds, bid)
		}
	}
	err = l.svcCtx.Activity.UpdateBindRel(l.ctx, nil, data.ID, bindRel)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &promotion.BaseResp{
		Msg: i18n.DeleteSuccess,
	}, nil
}
